package com.study.sbsummary.context;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.study.sbsummary.config.constant.CodeEnum;
import com.study.sbsummary.wrapper.SessionWrapper;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartResolver;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 10400
 * @create 2017-05-23 19:00
 */
public class BaseController implements ServletContextAware {
    /**
     * 日志
     **/
    protected final Logger log = LoggerFactory.getLogger(BaseController.class);

    @Autowired(required = false)
    public HttpServletRequest request;
    @Autowired(required = false)
    public HttpServletResponse response;
    @Deprecated
    public HttpSession session;
    public ServletContext application;
    /**
     * 文件
     **/
    @Autowired(required = false)
    protected MultipartResolver multipartResolver;
    @Autowired
    private SessionWrapper sessionWrapper;

    /**
     * @param code
     * @return
     */
    public static String respJson(CodeEnum code) {
        return respJson(code, null);
    }

    /**
     * @param code
     * @param data
     * @return
     */
    public static String respJson(CodeEnum code, Object data) {
        JSONObject jsono = new JSONObject();
        jsono.put("code", code.getCode());
        jsono.put("status", code.getReason());
        if (data != null) {
            jsono.put("data", data);
        }
        return jsono.toJSONString();
    }

    /**
     * @param code   错误码
     * @param status 内容
     * @return
     */
    public static String respJson(String code, String status) {
        return respJson(code, status, null);
    }

    /**
     * @param code
     * @param message
     * @param data
     * @return
     */
    public static String respJson(String code, String message, Object data) {
        JSONObject jsono = new JSONObject();
        jsono.put("code", code);
        jsono.put("message", message);
        if (data != null) {
            jsono.put("data", data);
        }
        return JSON.toJSONString(jsono);
    }

    /*@ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }*/

    @Override
    public void setServletContext(ServletContext arg0) {
        this.application = arg0;
    }

    /**
     * 获取传递过来的参数
     */
    public String getParameter(String key) {
        return request.getParameter(key);
    }

    /**
     * 分页对象
     */
    public <T> Page<T> getPage(Class<T> clazz) {
        Page<T> page = new Page<T>();
        String currentPage = getParameter("currentPage");
        String pageSize = getParameter("pageSize");
        currentPage = currentPage == null || "".equals(currentPage) ? "1" : currentPage;
        pageSize = pageSize == null || "".equals(pageSize) ? "10" : pageSize;
        page.setSearchCount(true);
        page.setSize(Integer.valueOf(pageSize));
        page.setCurrent((Integer.valueOf(currentPage)));
        return page;
    }

    protected String redirectOuter(String url) {
        return "redirect:" + url;
    }

    protected long getUserId() {
//        Object userid = session.getAttribute("userid");
//        return (String)userid;
//        return 0L;
//        try {
//            SessionUserInfoDTO userInfoDTO = sessionWrapper.getUserSession(this.getSessionId());
//            if (userInfoDTO != null) {
//                ThreadLocalContextHolder.put("userInfo", userInfoDTO);
//                return userInfoDTO.getUserid();
//            }
//        } catch (Exception e) {
//            log.error("获得session异常: ", e);
//        }
//        return 1230895852L;
        return 1L;
    }

    private String getSessionId() {
        String jsessionId = request.getSession().getId();
        if (StringUtils.isEmpty(jsessionId)) {
            jsessionId = "constant-session-0";
        }
        return jsessionId;
    }

    /**
     * binder用于bean属性的设置
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new DateEditor());
        binder.registerCustomEditor(String.class, new StringEscapeEditor());
    }

    /**
     * 获取传递过来的str参数,并给默认值
     */
    public String getStrParameter(String key, String defaultValue) {
        String str = getParameter(key);
        if (StringUtils.isEmpty(str)) {
            return defaultValue;
        }
        return str.trim();
    }
}

/**
 * 处理日期格式转换问题
 */
class DateEditor extends PropertyEditorSupport {
    Pattern pattern = Pattern.compile("[^0-9]");

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (StringUtils.isBlank(text)) {
            return;
        }
        text = text.trim();
        Matcher matcher = pattern.matcher(text);
        text = matcher.replaceAll("");

        int length = text.length();
        Date date;
        switch (length) {
            case 14:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyyMMddHHmmss")).toDate();
                break;
            case 12:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyyMMddHHmm")).toDate();
                break;
            case 10:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyyMMddHH")).toDate();
                break;
            case 8:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyyMMdd")).toDate();
                break;
            case 6:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyyMM")).toDate();
                break;
            case 4:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyy")).toDate();
                break;
            default:
                return;
        }
        setValue(date);
    }
}

/**
 * 处理string类型两头空白
 */

class StringEscapeEditor extends PropertyEditorSupport {

    public StringEscapeEditor() {
        super();
    }

    @Override
    public String getAsText() {
        Object value = getValue();
        return value != null ? value.toString() : "";
    }

    @Override
    public void setAsText(String text) {
        if (text == null) {
            setValue(null);
        } else {
            String value = text;
            value = value.trim();
            setValue(value);
        }
    }
}